<?php
//商品
class Goods extends Data_Base
{
    public static function factory ($type, $nid)
    {
        $type = strtoupper($type);

        switch ($type)
        {
        case 'TRACK':
            return new App_Track($nid);
            break;

        case 'ACTIVITY':
            return new App_Activity($nid);
            break;
        
        case 'ZIYING':
            return new Ziying($nid);
            break;
        
        default: 
            throw new Exception("无效 $type ");
        }
    }

    public static function optionsGoodsType ()
    {
        return array('ACTIVITY' => '活动', 'TRACK' => '路线','ZIYING'=>'自营');
    }

    public static function orderGoodsTypeName ($type)
    {
        switch ($type)
        {
            case 'ACTIVITY':
                return '活动';
                break;

            case 'TRACK';
                return '路线';
                break;

            case 'ZIYING';
                return '自营';
                break;

            default: 
                return '未知';
                break;
        }
    }

    public function __construct ($nid)
    {
        $this->_nid = $nid;
    }

	//商品基本信息
	//$goodsId		商品编号
	//$attrId		属性编号
	//$buyQuantity	购买数
    public static function basicInfo ($type, $goodsId, $attrId = NULL, $buyQuantity = 0, $days, $buyType = 'normal')
    {
        if ($type == 'ACTIVITY')
            $goods = new App_Activity($goodsId);
        else 
            $goods = new App_Track($goodsId);

        $info = $goods->detail();
        $desc = App_Goods_Attr::descript($attrId);
        
        $info['attr'] = array(
            'id'    => $attrId,
            'desc' => '',
            'positionNumber' => '',
            'barCode' => '',
        );
        
        if ($buyQuantity > 0)
        {
            $price = $goods->getPrice();
            $money = $price * $buyQuantity * $days;
            $info['money'] = array(
                'price'    => $price,
                'quantity' => $buyQuantity,
                'persons'  => $buyQuantity,
                'money'    => $money,
            );
        }
            
        return $info;
    }

    public static function goodsInfoGroupByShop ($arrGoodsInfo)
    {
        $ret = array();
        foreach ($arrGoodsInfo as $goods)
        {
            $shopId = Arr::get($goods, 'shopId');
            if (! array_key_exists($shopId, $ret))
                $ret[$shopId] = array(
                    'goods'    => array(),
                    'shopName' => App_Shop::name($shopId),
                    'goodsId' => $shopId,
                );

            $ret[$shopId]['goods'][] = $goods;
        }

        return $ret;
    }

	//总额
    public static function getMoney ($arrGoodsBuyInfo)
    {
        $n = 0;
        foreach ($arrGoodsBuyInfo as $rs)
        {
            $price = $rs['goodsPrice'];
            $quantity = $rs['goodsQuantity'];

            $n += $price * $quantity;
        }

        return $n;
    }

    // 开团最少人数
    public static function getTuanPersons($nid)
    {
        $info = self::info($nid);
        $n = Arr::get($info, 'tuanPersons', NULL);
        if ($n <= 0)
            return 0;
        else
            return min($n, 10);
    }

	//商品缩略图
    public function getThumb ()
    {
        return DB::select('thumb')
            ->from('tiyu_goods')
            ->where('id', '=', $this->_nid)
            ->limit(1)
            ->execute()
            ->get('thumb');
    }

	//添加商品数
    public function incCounts ($type)
    {
        $query = "UPDATE tiyu_goods set $type=$type+1 WHERE id=" . $this->_nid;
        $rows = DB::query(Database::UPDATE, $query)->execute();

        return $rows > 0;
    }

    // 给收藏和评论过得发消息
    public function pushAppMessage()
    {
        $like = new App_Like('goods', $this->_nid);
        $uidsLiked = $like->uidListByLiked();
        $comm = new App_Comments('goods', $this->_nid);
        $uidsCommt = $comm->uidListByCommented();

        $info  = self::info($this->_nid);
        $title = $info['name'];
        $url   = $info['url'];
        $message = "商品内容有更新啦";

        $uids = array_unique(array_merge($uidsLiked, $uidsCommt));
        $alias = array();
        foreach ($uids as $uid)
        {
            $alias[] = 'u'.$uid;

            $toUid = $uid;
            $fromUid = 0;
            $type = 'gonglue';
            $typeNid = $this->_nid;
            $image   = $info['thumb'];
            $url     = $info['url'];
            App_Message::record($toUid, $fromUid, $message, $type, $typeNid, $image, $url);
        }

        if (! empty($alias))
        {
            $activityName = 'ArticleActivity';
            $push = new JPush;
            $push->alert_2_aliaslist($alias, $title, $message, $url, $activityName);
        }
    }

	//通过id显示商品列表
	//$goodsIds array 商品编号
    public static function listByGoodsIds ($goodsIds)
    {
        $user = User::currentUser();
        if (empty($goodsIds))
            return array();

        $query = DB::select()
            ->from('tiyu_goods')
            ->where('id', 'in', $goodsIds)
            ->execute();

        $goodsList = array();
        foreach ($query as $rs)
        {
            $id = $rs['id'];
            $rs['nid']   = $id;
            $rs['price']     = '￥'.number_format($rs['price'] / 100, 2);
            $rs['origPrice'] = '￥'.number_format($rs['origPrice'] / 100, 2);
            $rs['isLiked'] = $user->hasLiked('goods', $rs['nid']);
            $rs['thumb']   = self::imageSrc($rs['thumb']);

            $goodsList[$id] = $rs;
        }

        $ret = array();
        foreach ($goodsIds as $goodsId)
        {
            if (isset($goodsList[$goodsId]))
                $ret[] = $goodsList[$goodsId];
        }

        return $ret;
    }

	//最新商品列表
    public static function listByNewest ($shopId, $offset, $limit)
    {
        $user = User::currentUser();
        $query = DB::select()
            ->from('tiyu_goods')
            ->where('shopId', '=', $shopId)
            ->order_by('created', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->execute();

        $goodsList = array();
        foreach ($query as $rs)
        {
            $id = $rs['id'];
            $rs['nid']   = $id;
            $rs['price'] = '￥'.number_format($rs['price'] / 100, 2);
            $rs['origPrice'] = '￥'.number_format($rs['origPrice'] / 100, 2);
            $rs['isLiked'] = $user->hasLiked('goods', $rs['nid']);
            $rs['thumb']   = self::imageSrc($rs['thumb']);

            $goodsList[$id] = $rs;
        }

        return $goodsList;
 
    }

	// 商铺商品列表
    public static function listByShop ($shopId, $arrOrderBy, $offset, $limit)
    {
        $user = User::currentUser();
        $query = DB::select()
            ->from('tiyu_goods')
            ->where('shopId', '=', $shopId)
            ->order_by($arrOrderBy[0], $arrOrderBy[1])
            ->offset($offset)
            ->limit($limit)
            ->execute();

        $goodsList = array();
        foreach ($query as $rs)
        {
            $id = $rs['id'];
            $rs['nid']   = $id;
            $rs['price'] = '￥'.number_format($rs['price'] / 100, 2);
            $rs['origPrice'] = '￥'.number_format($rs['origPrice'] / 100, 2);
            $rs['isLiked'] = $user->hasLiked('goods', $rs['nid']);
            $rs['thumb']   = self::imageSrc($rs['thumb']);
            $rs['url']     = 'http://'.Arr::get($_SERVER, 'HTTP_HOST', 'www.youzigouwu.com').'/goods/detail/'.$id;
            $rs['tuanUrl'] = 'http://'.Arr::get($_SERVER, 'HTTP_HOST', 'www.youzigouwu.com').'/goods/tuan/'.$id;
            $goodsList[$id] = $rs;
        }

        return $goodsList;
 
    }

    

    public static function search ($key, $sort_by = NULL, $offset = 0, $limit = 10, $tag = NULL)
    {
        if (empty($sort_by))
            $sort_by = 'changed_desc';

        list($sort, $by) = explode('_', $sort_by);

        $where = array();
        $where[] = array('name', 'like', "%$key%");

        if ($tag > 0)
            $where[] = array('tag', '=', $tag);

        $count = self::counts('tiyu_goods', $where);
        $lists = self::lists ('tiyu_goods', $where, array($sort, $by), $offset, $limit);

        $user  = user::currentUser();
        foreach ($lists as & $rs)
        {
            unset($rs['description']);

            $rs['nid']      = $rs['id'];
            $rs['price']    = '￥'.number_format($rs['price'] / 100, 2);
            $rs['origPrice']= '￥'.number_format($rs['origPrice'] / 100, 2);
            $rs['isLiked']  = $user->hasLiked('goods', $rs['nid']);
            $rs['thumb']    = self::imageSrc($rs['thumb']);
            $rs['url']      = 'http://'.Arr::get($_SERVER, 'HTTP_HOST', 'www.youzigouwu.com').'/goods/detail/'.$rs['id'];
            $rs['tuanUrl']  = 'http://'.Arr::get($_SERVER, 'HTTP_HOST', 'www.youzigouwu.com').'/goods/tuan/'.$rs['id'];
        }

        return array('total' => $count, 'list' => $lists);
    }

	//收藏商品
	//$uid 用户id
	//$tag 标记
    public static function likeItemsByUid ($uid, $offset, $limit, $tag = NULL)
    {
        if ($uid == 0)
        {
            $count = 0;
            $list  = array();
        }
        else
        {
	        $count = DB::select('a.id')
	            ->from(array('tiyu_goods', 'a'))
	            ->join(array('user_v2_actions', 'b'), 'LEFT')
	            ->on('b.type', '=', DB::expr("'goods'"))
	            ->on('a.id', '=', 'b.nid')
	            ->where('b.uid', '=', $uid);

            if ($tag > 0)
            {
                $count = $count->where('a.tag', '=', $tag)
                    ->execute()->count();
            }
            else
            {
                $count = $count->execute()->count();
            }
	
	        $list = DB::select('a.name', 'a.thumb', 'a.id', 'a.countsLike', 'a.price', 'b.uid', 'b.created')
	            ->from(array('tiyu_goods', 'a'))
	            ->join(array('user_v2_actions', 'b'), 'LEFT')
	            ->on('b.type', '=', DB::expr("'goods'"))
	            ->on('a.id', '=', 'b.nid')
	            ->where('b.uid', '=', $uid)
	            ->order_by('b.created', 'desc')
	            ->offset($offset)
	            ->limit($limit);

            if ($tag > 0)
            {
                $list = $list->where('a.tag', '=', $tag)
                    ->execute()->as_array();
            }
            else
            {
                $list = $list->execute()->as_array();
            }

            foreach ($list as & $rs)
            {
                $rs['price'] = '￥'. number_format($rs['price'] / 100, 2);
            }
        }

        return array('total' => $count, 'list' => $list);
    }

    public function share ($user)
    {
        $action = 'share';
        $update = array('countsShare' => DB::expr('`countsShare` + 1'));

        $rows = DB::update('tiyu_goods')
            ->set($update)
            ->where('id', '=', $this->_nid)
            ->execute();
    }



	//收藏商品
	//$user object 用户对象
    public function like ($user)
    {
        $action = 'like';

        // user action
        if ($user->hasAction('goods', $this->_nid, $action))
        {
            $user->delAction('goods', $this->_nid, $action);
            $update = array('countsLike' => DB::expr('`countsLike` - 1'));
        }
        else
        {
            $user->addAction('goods', $this->_nid, $action);
            $update = array('countsLike' => DB::expr('`countsLike` + 1'));
        }

        $rows = DB::update('tiyu_goods')
            ->set($update)
            ->where('id', '=', $this->_nid)
            ->execute();

        if ($rows > 0)
        {
            $n = DB::select('countsLike')
                ->from('tiyu_goods')
                ->where('id', '=', $this->_nid)
                ->execute()
                ->get('countsLike');

            return $n;
        }
        else
        {
            return FALSE;
        }
    }

    public static function options_all_goods ()
    {
        $query = DB::select('id', 'name', 'shopId')
            ->from('tiyu_goods')
            ->order_by('changed', 'desc')
            ->execute();

        $ret = array();
        $shopId = App_Shop_Manager::currentShopId();
        foreach ($query as $rs)
        {
            if ($shopId > 0)
            {
                if ($shopId == $rs['shopId'])
                    $ret[$rs['id']] = $rs['name'];
            }
            else
            {
                $ret[$rs['id']] = $rs['name'];
            }
        }

        return $ret;
    }

	//商品信息
    public static function info ($nid)
    {
        $detail = self::item('tiyu_goods', 'id', $nid);
        if (empty($detail))
            return array();

        $detail['rawPrice']     = $detail['price'];
        $detail['rawTuanPrice'] = $detail['tuanPrice'];
        $detail['price']        = '￥'. number_format($detail['price'] / 100, 2);
        $detail['origPrice']    = '￥'. number_format($detail['origPrice'] / 100, 2);
        $detail['tuanPrice']    = '￥'. number_format($detail['tuanPrice'] / 100, 2);

        return array(
            'name' => $detail['name'],
            'id'   => $detail['id'],
            'nid'  => $detail['id'],
            'price'=> $detail['price'],
            'origPrice'=> $detail['origPrice'],
            'rawPrice' => $detail['rawPrice'],
            'thumb'    => $detail['thumb'],
            'thumbsrc' => $detail['thumb'],
            'url'            => 'http://'.Arr::get($_SERVER, 'HTTP_HOST', 'www.youzigouwu.com').'/goods/detail/'.$nid,
            'tuanUrl'        => 'http://'.Arr::get($_SERVER, 'HTTP_HOST', 'www.youzigouwu.com').'/goods/tuan/'.$nid,
            'positionNumber' => $detail['positionNumber'],
            'barCode'        => $detail['barCode'],
            'shopId'         => $detail['shopId'],
            'countsLike'     => $detail['countsLike'],
            'countsShare'    => $detail['countsShare'],
            'rawTuanPrice'   => $detail['rawTuanPrice'],
            'tuanPrice'      => $detail['tuanPrice'],
            'tuanPersons'    => $detail['tuanPersons'],
            'shortDesc'      => $detail['shortDesc'],
            'shaiMoney'      => $detail['shaiMoney'],
        );
    }

    public static function addCountsView ($goodsNid, $incNumber)
    {
        $rows = DB::update('tiyu_goods')
            ->set(array('countsView' => DB::expr("`countsView` + $incNumber")))
            ->where('id', '=', $goodsNid)
            ->limit(1)
            ->execute();

        return $rows > 0;
    }

    // 商品的仓储号(货位号，条码)
    public static function storageCode ($goodsNid, $attrId)
    {
        if ($attrId > 0)
        {
            $ret = array(
                'barCode' => App_Goods_Attr::barCode($attrId),
                'positionNumber' => App_Goods_Attr::positionNumber($attrId),
            );

            return $ret;
        }
        else
        {
            $info = self::info($goodsNid);
            return array(
                'barCode' => Arr::get($info, 'barCode', ''),
                'positionNumber' => Arr::get($info, 'positionNumber', ''),
            );
        }

    }

	//商品详细
    public static function detail ($nid, $type = 'normal')
    {
        $type   = strtoupper($type);
        $detail = self::item('tiyu_goods', 'id', $nid);
        if (empty($detail))
            return array();


        $detail['price']     = '￥'. number_format($detail['price'] / 100, 2);
        $detail['origPrice'] = '￥'. number_format($detail['origPrice'] / 100, 2);
        $detail['thumb']     = explode('|', $detail['thumb']);
        $detail['images']    = explode('|', $detail['images']);
        $detail['thumbsrc']  = $detail['thumb'][0];
        $detail['attr']      = App_Goods_Attr::attrs_with_values($nid);
        $detail['origTuanPrice'] = $detail['tuanPrice'];
        $detail['tuanPrice'] = '￥'. number_format($detail['tuanPrice'] / 100, 2);
        $detail['url']       = url::site('/goods/detail/'.$nid, 'http', FALSE);
        $detail['tuanUrl']   = url::site('/goods/tuan/'.$nid, 'http', FALSE);
        $detail['salesMonth']= self::countsCurrentMonthSales($nid);

        if ($type == 'TUAN')
        {
            foreach ($detail['attr']['values'] as & $rs)
                $rs['price'] = $detail['origTuanPrice'] / 100;
        }

        return $detail;
    }

    // 同步商品售卖数量
    public static function syncCountsSale ($goodsNid)
    {
        $counts = self::countsGoodsSales($goodsNid);
        $query  = DB::update('tiyu_goods')
            ->set(array('countsSale' => $counts))
            ->where('id', '=', $goodsNid)
            ->execute();
    }

    // 商品总销量
    public static function countsGoodsSales($goodsNid, $tStart = NULL, $tStop = NULL)
    {
        $query  = DB::select(DB::expr("sum(g.quantity) as sum"))
            ->from(array('app_order', 'o'))
            ->join(array('app_order_goods', 'g'), 'LEFT')
            ->on('o.id', '=', 'g.orderId')
            ->where('o.status', '>', 0)
            ->where('g.goodsId', '=', $goodsNid);

        if ($tStart > 0)
            $query->where('o.created', '>=', $tStart);

        if ($tStop > 0)
            $query->where('o.created', '<=', $tStop);

        $count = $query->execute()->get('sum');

        if (empty($count))
            return 0;
        else
            return $count;
    }


    // 本月商品销量
    public static function countsCurrentMonthSales($goodsNid)
    {
        $tStart = strtotime(date("Ym01"));

        $tStart = mktime(0, 0 , 0,date("m"),1,date("Y"));
        $tStop  = mktime(23,59,59,date("m"),date("t"),date("Y"));

        return self::countsGoodsSales($goodsNid, $tStart, $tStop);
    }
}
